#include "browser.h"
#include "browsermainwindow.h"

Browser::Browser()
{
    // 自定义初始化配置类实例
    m_customProfile = QWebEngineProfile::defaultProfile();
    // 设置无痕浏览模式
//    m_customProfile->setHttpCacheType(QWebEngineProfile::NoCache);

    // TODO，各个模块初始化配置

    // 下载器实例化及配置
    downloadWindow = new DownloadWindow();
    // 设置默认下载路径
    m_customProfile->setDownloadPath(ConfigManager::getInstance().getDownloadPath());
    QObject::connect(m_customProfile, &QWebEngineProfile::downloadRequested, downloadWindow, &DownloadWindow::downloadRequest);
//    m_downloadManagerWidget.setAttribute(Qt::WA_QuitOnClose, false);

    // 设置密码保存请求拦截器(depreted,方法不可行，不适用)
    LoginPasswordInterceptor *loginPasswordInterceptor = new LoginPasswordInterceptor();
    m_customProfile->setUrlRequestInterceptor(loginPasswordInterceptor);
    UrlDetectInterceptor *urlInterceptor = new UrlDetectInterceptor();
    m_customProfile->setUrlRequestInterceptor(urlInterceptor);

    // 实例化各个组件
    pluginMangerWindow = new PluginManagerWindow();
}

QVector<BrowserMainWindow *> Browser::windows()
{
    return this->m_windows;
}

BrowserMainWindow *Browser::createWindow(bool offTheRecord)
{
//    QWebEngineProfile *profile = offTheRecord ? &m_customProfile : QWebEngineProfile::defaultProfile();
    QWebEngineProfile *profile = m_customProfile;
    BrowserMainWindow * window = new BrowserMainWindow(this, nullptr, profile);
    // 维护打开的窗口
    m_windows.append(window);
    QObject::connect(window, &QObject::destroyed, [this, window]() {
        m_windows.removeOne(window);
    });

    //
    QObject::connect(window, &BrowserMainWindow::showDownloadWindow, [=](){
       this->downloadWindow->show();
       this->downloadWindow->activateWindow();
    });

    // 设置窗口组件
    window->setPluginManagerWindow(pluginMangerWindow);
    return window;
}
